﻿using System.Dynamic;
using System.Linq;
using ABC.XPath;
using ABC.XPath.NodePolicy;

namespace ABC.Mvc
{
	public class ExpandoObjectNodePolicy : CollectionNodePolicyBase
	{
		/// <summary>
		/// Gets the node policy object.
		/// </summary>
		/// <returns>Returns an instance of this node policy.</returns>
		public static new INodePolicy GetPolicy()
		{
			return new ExpandoObjectNodePolicy();
		}

		/// <summary>
		/// Creates a new <see cref="ABC.Dictionary.Util.DictionaryNodePolicy"/> instance.
		/// </summary>
		protected ExpandoObjectNodePolicy() { }

		/// <summary>
		/// See <see cref="INodePolicy.GetAttributesCount"/> for details.
		/// </summary>
		public override int GetAttributesCount( Node node )
		{
			return 0;
		}

		/// <summary>
		/// See <see cref="INodePolicy.GetName"/> for details.
		/// </summary>
		public override string GetName( Node node )
		{
			return "ViewData";
		}

		/// <summary>
		/// See <see cref="INodePolicy.GetChildrenCount"/> for details.
		/// </summary>
		public override int GetChildrenCount( Node node )
		{
			return ( (ExpandoObject)node.Object ).Count();
		}

		/// <summary>
		/// See <see cref="INodePolicy.GetChild"/> for details.
		/// </summary>
		public override Node GetChild( Node node, int index )
		{
			var expandoObject = (ExpandoObject)node.Object;

			if( index >= 0 && index < expandoObject.Count() )
			{
				var item = expandoObject.ElementAtOrDefault( index );

				var childNode = CreateChildNode( item.Value, node );
				childNode.Name = item.Key;
				return childNode;
			}

			return null;
		}
	}
}
